import sys, webbrowser

from PyQt6.QtWidgets import \
    QApplication, QToolBox, QVBoxLayout, QToolButton, QGroupBox
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QIcon


class MyToolBox(QToolBox):
    def __init__(self):
        super(MyToolBox, self).__init__()
        self.resize(280, 300)
        self.setWindowTitle('QToolBox 测试')
        self.setWindowFlag(Qt.WindowType.Dialog)

        # 列表项
        list = [
            {
                'title': '南京部分大学',
                'categories': [
                    {'des': '南京大学', 'pic': 'images/nju.png',
                     'url': 'https://www.nju.edu.cn'},
                    {'des': '东南大学', 'pic': 'images/seu.ico',
                     'url': 'https://www.seu.edu.cn'},
                    {'des': '南京师范大学', 'pic': 'images/nnu.ico',
                     'url': 'https://www.nnu.edu.cn'},
                ]
            },
            {
                'title': '北京部分出版社',
                'categories': [
                    {'des': '电子工业出版社', 'pic': 'images/phei.png',
                     'url': 'https://www.phei.com.cn/'},
                    {'des': '人民邮电出版社', 'pic': 'images/ptpress.ico',
                     'url': 'https://www.ptpress.com.cn'},
                    {'des': '清华大学出版社', 'pic': 'images/tup.ico',
                     'url': 'https://www.tup.tsinghua.edu.cn'},
                    {'des': '机械工业出版社', 'pic': 'images/cmpbook.ico',
                     'url': 'https://www.cmpbook.com'},
                ]
            }
        ]
        for item in list:
            gpbox = QGroupBox()
            self.addItem(gpbox, item['title'])

            layout = QVBoxLayout(gpbox)
            layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
            for category in item['categories']:
                toolButton = QToolButton()
                toolButton.setText(category['des'])
                toolButton.setIcon(QIcon(category['pic']))
                toolButton.setIconSize(QSize(64, 16))
                toolButton.setAutoRaise(True)
                toolButton.setToolButtonStyle(\
                    Qt.ToolButtonStyle.ToolButtonTextUnderIcon)
                toolButton.url = category['url']
                layout.addWidget(toolButton)
                toolButton.clicked.connect(\
                    #sss
                    lambda: webbrowser.open(self.sender().url))

        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyToolBox()
    ex.show()
    sys.exit(app.exec())
